package com.ssm.ioc;

import com.ssm.ano.Controller;
import com.ssm.ano.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class RelationUtil {
    private static final Logger log = LoggerFactory.getLogger(RelationUtil.class);

    /**
     * 建立Bean 类与实例的映射关系
     */
    public static Map getBeanMap() {
        Map<Class<?>, Object> beanMap = new HashMap<Class<?>, Object>();
        Set<Class<?>> beanSet = ClassHelper.getBeanClass();
        for (Class<?> myClass : beanSet) {
            Object object = ReflectUtil.getInstance(myClass);
            beanMap.put(myClass, object);
        }
        return beanMap;
    }

    /**
     * 建立方法与注释中value 的映射关系
     */
    public static Map getMethodMap() {
        Map<String, Method> methodMap = new HashMap<String, Method>();
        Set<Class<?>> ControllerSet = ClassHelper.getControllerClass();
        for (Class<?> myClass : ControllerSet) {
            //获取Controller 注释
            Controller controller = (Controller) myClass.getAnnotation(Controller.class);
            //获取注释上的value 值
            String cValue = controller.value();
            //获取所有的方法
            Method[] methods = myClass.getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping rm = (RequestMapping) method.getAnnotation
                            (RequestMapping.class);
                    String rValue = rm.value();
                    methodMap.put("/" + cValue + "/" + rValue, method);
                } else {
                    continue;
                }
            }
        }
        return methodMap;
    }
}